package com.apache.bid.service.cacheplugins;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.cache.util.Validator;

/**
 * session的浏览次数控制插件
 * @author admin
 *
 */
public class SessionBrowsingTimesPluginImpl implements PluginConnector {

	private Logger log = Logger.getLogger(getClass());
	private ProxyManager wbdProxyCacheManager;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 */
	public Object execute(ParamsVo param) throws Exception {
		ResultEntity entity = new ResultEntity();
		long browsingTimes = 0;
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("session");
		String sessionId = String.valueOf(param.getParams("sessionId"));
		if (Validator.isNull(sessionId)) {
			String sessionIdList = String.valueOf(param.getParams("sessionIdList"));
			if (Validator.isNull(sessionIdList)) {
				entity.setResult("false");
				return entity;
			}
			String[] sesIdArray = sessionIdList.split(",");
			Map<String, String> maprt = new HashMap<String, String>();
			for (String sid : sesIdArray) {
				browsingTimes = browsingTimes(cache, sid);
				String key = BidCacheManager.sessionBrowsing_prefix + sid;
				cache.createCacheObject(key, String.valueOf(browsingTimes));
				List itemIds = (List) cache.getCacheObjectByKey("bidSessionItemIds_" + sid);
				JSONObject json = new JSONObject();
				json.put("browsing", String.valueOf(browsingTimes));
				if (!Validator.isEmpty(itemIds)) {
					json.put("itemNum", String.valueOf(itemIds.size()));
				} else {
					json.put("itemNum", "0");
				}
				log.info("活动[" + sid + "]所计算的随机浏览次数：" + browsingTimes);
				maprt.put(sid, json.toString());
			}
			entity.setEntity(maprt);
		} else {
			String key = BidCacheManager.sessionBrowsing_prefix + sessionId;
			browsingTimes = browsingTimes(cache, sessionId) + 1;
			cache.createCacheObject(key, String.valueOf(browsingTimes));
			log.info("活动[" + sessionId + "]所计算的随机浏览次数：" + browsingTimes);
			entity.setEntity(browsingTimes);
		}
		entity.setResult("true");
		entity.setMessage("加载完成");
		return entity;
	}

	private long browsingTimes(BidCacheManager cache, String sid) {
		long browsingTimes = 0;
		String key = BidCacheManager.sessionBrowsing_prefix + sid;
		if (cache.checkCacheObject(key)) {
			Object count = cache.getCacheObjectByKey(key);
			if (count != null) {
				browsingTimes = Long.parseLong(String.valueOf(count));
			} else {
				browsingTimes = getRandomX();//初始化随机数
			}
		} else {
			browsingTimes = getRandomX();//初始化随机数
		}
		return browsingTimes;
	}

	private static long getRandomX() {
		//随机产生100~500以内的随机数; 
		int min = 100;
		int max = 500;
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;

	}

	public void setWbdProxyCacheManager(ProxyManager wbdProxyCacheManager) {
		this.wbdProxyCacheManager = wbdProxyCacheManager;
	}
}